package cn.connorma.example.oauth.github;

import cn.connorma.example.oauth.github.handlers.LoginCallBackRestHandler;
import cn.connorma.example.oauth.github.handlers.RootRestHandler;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpUtil;
import com.google.gson.Gson;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * github oauth流程服务端
 * 使用hutool的简易http server
 *
 * @author matian
 * @date 2023-02-13 15:30:40
 */
public class ExampleServerMain {

    public static final Gson GSON = new Gson();

    /**
     * github oauth app client id
     * 从main函数args[0]读取
     */
    public static String CLIENT_ID;
    /**
     * github oauth app client secret
     * 从main函数args[1]读取
     */
    public static String CLIENT_KEY;

    public static void main(String[] args) {
        CLIENT_ID = args[0];
        CLIENT_KEY = args[1];
        System.out.println("read oauth app prop from main args: client id:" + CLIENT_ID + ", client secret:" + CLIENT_KEY);

        HttpUtil.createServer(9988)
                .addAction("/", (req, res) -> {
                    res.setContentType(ContentType.TEXT_HTML.getValue());
                    res.setCharset(StandardCharsets.UTF_8);
                    Result result = new RootRestHandler().handle(req);
                    res.write(GSON.toJson(result));
                    res.close();
                })
                .addAction("/login.html", (req, res) -> {
                    res.setContentType(ContentType.TEXT_HTML.getValue());
                    res.setCharset(StandardCharsets.UTF_8);
                    InputStream in = ExampleServerMain.class.getClassLoader().getResourceAsStream("static/login.html");
                    res.write(in);
                    res.close();
                })
                // github oauth回调处理
                // 此地址在github创建oauth app时设置Authorization callback URL为此路径
                .addAction("/oauth/github/callback", (req, res) -> {
                    res.setContentType(ContentType.JSON.getValue());
                    res.setCharset(StandardCharsets.UTF_8);
                    Result result = new LoginCallBackRestHandler().handle(req);
                    res.write(GSON.toJson(result));
                    res.close();
                })
                .start();
    }

}
